# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能，如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块

# import xbot
# from xbot import print, sleep
# from . import package
import datetime
import json
import sys
from decimal import Decimal

import requests

import numpy
import xlrd

from wechat.vedio import chatData, uploadImg


def main(args):
    pass
from collections import Counter
import uiautomator2 as u2
import time
import re
import os, subprocess, random
import threading
import pyperclip
from wechat.vedio.tools import upload_data, upload_img, get_token, get_search_data, error_log, notice

# adb_path = "C:\\Users\\Admin\\Desktop\\platform-tools\\"
# adb_path = "C:\\Users\\有赞\\Desktop\\platform-tools\\"
adb_path = "C:\\android-sdk-windows\\platform-tools\\"


def excute_cmd(cmd):
    return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True, encoding='UTF-8').stdout

def intoWechat(d):
    print("intoWechat")
    condition = d.app_current()

    if condition["package"] != 'com.tencent.mm':
        d.app_start("com.tencent.mm")
        if not d(text="发现").exists:
            d.app_stop("com.tencent.mm")
            d.uiautomator.stop()
            d.uiautomator.start()
            d.app_start("com.tencent.mm")
    else:
        d.app_stop("com.tencent.mm")
        d.uiautomator.stop()
        d.uiautomator.start()
        d.app_start("com.tencent.mm")

    time.sleep(1)
    d(text="发现").click()
    time.sleep(1)
    d(text="视频号").click()
    time.sleep(2)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').click()
    if d.xpath(
        "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").exists:
        d.xpath(
            "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").click()
    if d.xpath('//*[@resource-id="com.tencent.mm:id/amj"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/amj"]').click()
    time.sleep(1)
    toSearchPage(d)

def intoWechatMain(d):
    print("intoWechat")
    condition = d.app_current()

    if condition["package"] != 'com.tencent.mm':
        d.app_stop("com.tencent.mm")
        d.uiautomator.stop()
        d.uiautomator.start()
        d.app_start("com.tencent.mm")
    else:
        d.app_stop("com.tencent.mm")
        d.uiautomator.stop()
        d.uiautomator.start()
        d.app_start("com.tencent.mm")

def restartWechat(d):
    print("intoWechat")
    d.app_stop("com.tencent.mm")
    d.uiautomator.stop()
    d.uiautomator.start()
    d.app_start("com.tencent.mm")
    time.sleep(1)
    d(text="发现").click()
    time.sleep(1)
    d(text="视频号").click()
    time.sleep(1)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/e1x"]').click()
    d.xpath(
        "//*[@resource-id='com.tencent.mm:id/kfj']/android.widget.FrameLayout/android.widget.RelativeLayout").click()
    time.sleep(1)
    toSearchPage(d)


def getNameFromXls(filename, by_index, colindex):
    data = xlrd.open_workbook(filename)#打开文件
    table = data.sheets()[by_index] #指定为哪一个sheet
    colnames = table.col_values(colindex)#指定哪一列从0开始
    return colnames

def toSearchPage(d):
    print("toSearchPage")
    time.sleep(5)
    d.xpath('//*[@resource-id="com.tencent.mm:id/j4u"]').wait(timeout=5)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/j4u"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/j4u"]').click()
    elif d.xpath('//*[@resource-id="com.tencent.mm:id/hd2"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/hd2"]').click()


#搜索视频号名称
def searchName(d, name):
    print("searchName")
    if d.xpath('//*[@resource-id="com.tencent.mm:id/exc"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/exc"]').click()
    if d.xpath('//*[@resource-id="com.tencent.mm:id/egd"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/egd"]').click()
    d(focused=True).send_keys(name)
    d.send_action('search')
    d.xpath('//*[@resource-id="com.tencent.mm:id/iix"]').wait(timeout=5)

    # 获取主题和位置
def getLiveTheme(d):
    theme = ""
    if d.xpath("//*[re:match(@text, '主题.*')]").exists:
        theme = d.xpath("//*[re:match(@text, '主题.*')]").get_text()[3:]
    return theme

#获取场观和热度
def getNums(d):
    print("getNums")
    str = "0人看过"
    time.sleep(6)
    if d.xpath("//*[re:match(@text, '.*.人看过')]").exists:
        str = d.xpath("//*[re:match(@text, '.*.人看过')]").get_text()
    # if d.xpath('//*[@resource-id="com.tencent.mm:id/ftj"]').exists:
    #     str = d.xpath('//*[@resource-id="com.tencent.mm:id/ftj"]').get_text()
    list = str.split("人看过")
    listRes =[0,0]
    if list[0].find("万") != -1:
        listRes.insert(0, int(eval(list[0][:-1]) * 10000))
    else:
        listRes.insert(0, int(list[0]))
    if list[1] != "":
        if list[1].find("万") != -1:
            i = list[1].index("万")
            listRes.insert(1, int(eval(list[1][3:i]) * 10000))
        else:
            j = list[1].index("热")
            listRes.insert(1, int(list[1][3:j]))
    return listRes

# 获取粉丝团人数
def getFansClubNum(d):
    print("getFansClubNum")
    fansClubNum = 0
    d.xpath('//*[@resource-id="com.tencent.mm:id/dmh"]').wait(timeout=1.0)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/dmh"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/dmh"]').click()
        if d(resourceId="com.tencent.mm:id/dmk", text="粉丝牌").exists:
            d(resourceId="com.tencent.mm:id/dmk", text="粉丝牌").click()
            if d(resourceId="com.tencent.mm:id/dn1").exists:
                d.xpath('//*[@resource-id="com.tencent.mm:id/dmz"]').wait(timeout=5.0)
            d(resourceId="com.tencent.mm:id/dng", text="加入粉丝团").click()
            #判断是否点击成功
            for i in range(1,5,1):
                if d(resourceId="com.tencent.mm:id/dng", text="加入粉丝团").exists:
                    d(resourceId="com.tencent.mm:id/dng", text="加入粉丝团").click()
                else:
                    break
            numStr = d.xpath('//*[@resource-id="com.tencent.mm:id/ctc"]').get_text()
            fansClubNum = int(numStr.split("：")[1][:-1])
            d.press("back")
            time.sleep(1)
    return fansClubNum

# 检测发送礼物入口
def checkGiftIcon(d):
    print("checkGiftIcon")
    if d.xpath('//*[@resource-id="com.tencent.mm:id/dmh"]').exists:
        return True
    else:
        return False

# 获取点赞数dqt
def getGoodJob(d):
    print("getZan")
    zanNum = 0
    zan = "0"
    if d.xpath('//*[@resource-id="com.tencent.mm:id/dpe"]').exists:
        zan = d.xpath('//*[@resource-id="com.tencent.mm:id/dpe"]').get_text()
    if zan.find("万") != -1:
        zanNum = int(eval(zan[:-1]) * 10000)
    else:
        zanNum = int(zan)
    return zanNum

# 获取福袋
def getbroadcastBlessBagFlaginteger(d):
    print("broadcastBlessBagFlaginteger")
    broadcastBlessBagFlaginteger = 0
    if d.xpath('//*[@resource-id="com.tencent.mm:id/dqt"]').exists:
        broadcastBlessBagFlaginteger = 1
    return broadcastBlessBagFlaginteger


def checkShopBag(d):
    print("checkShopBag")
    shopBagExist = False
    if d.xpath('com.tencent.mm:id/dz1').exists:
        shopBagExist = True
    return shopBagExist

def toGoodsBagTop(d):
    ty = 0.9
    for i in range(1,5,1):
        if d.xpath('com.tencent.mm:id/bqz').exists:
            break
        else:
            d.swipe(0.5, 0.637, 0.5, ty, 0.2)
            if d.xpath('com.tencent.mm:id/dz4').exists:
                continue
            else:
                d.xpath('com.tencent.mm:id/dz1').click()
                time.sleep(1)
                ty = 0.8


def getGoodsBagDetails(d):
    print("getGoodsBagDetails")
    listGoods = []
    if d.xpath('com.tencent.mm:id/dz1').exists:
        d.xpath('com.tencent.mm:id/dz1').click()
        time.sleep(1)
        toGoodsBagTop(d)
        lastIndex = 0
        # while 1:
        stopFlag = False
        stopSwipeFlag = False
        for j in range(1,4,1):
            for i in range(1,5,1):
                listGood = {}
                if d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView' % i).exists \
                        and d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView' % i).exists:
                    #获取标题
                    goodsTitle = d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView' % i).get_text()
                    if len(listGoods) > 0:
                        for l in range(len(listGoods)-1,-1,-1):
                            if goodsTitle == listGoods[l]["goodsTitle"]:
                                stopFlag = True
                                break
                        if stopFlag:
                            continue
                    listGood["goodsTitle"] = goodsTitle
                    #获取价格
                    if d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView' % i).exists:
                        price = d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView' % i).get_text()
                        price = int(Decimal(price[1:]) * 100)
                        listGood["price"] = price
                    #获取平台
                    if d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.TextView' % i).exists:
                        platform = d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.TextView' % i).get_text()
                        listGood["platform"] = platform
                    elif d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView' % i).exists:
                        platform = d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView' % i).get_text()
                        listGood["platform"] = platform
                    listGoods.append(listGood)
                    lastIndex = i
                if d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]' % lastIndex).exists:
                    if 1 == int(d.xpath('//*[@resource-id="com.tencent.mm:id/dz4"]/android.widget.FrameLayout[%d]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]' % lastIndex).get_text()):
                        stopSwipeFlag = True
                        d.press("back")
                        time.sleep(1)
                        break
            if stopSwipeFlag:
                break
            d.swipe(0.5, 0.8, 0.5, 0.26, 0.2)
        if d.xpath('com.tencent.mm:id/dz2').exists:
            d.press("back")
    # - | - |

    return listGoods

#处理视频号监控结果
def resultCheck(liveList,liveDetailDictList,existFlag, liveStatusFlag,name,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger):
    # 检测到刚开始直播，发送通知
    if liveStatusFlag == True:
        liveList.append(name)
        data = {
            "videoNumberName": name,
            "goodJob": goodJob,
            "hot": hot,
            "fansClubNum": fansClubNum,
            "videoBroadcastGoodsList": videoBroadcastGoodsList,
            "startedAt": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
            "title": title,
            "type": 1,
            "broadcastBlessBagFlag": broadcastBlessBagFlaginteger,
            "userView": watchedNum,
            "snapPic": livingPhotoUrl,
            "endedAt": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
            "viewTrendList": [{"ts": int(round(time.time() * 1000)),
                               "v": watchedNum}]
        }
        liveDetailDictList.append(data)
        notice(name, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
        upload_data(data)
    else:
        print("not in living")
    return liveList, liveDetailDictList

    # print("resultCheck")
    # if existFlag == False and liveStatusFlag == True:
    #     liveList.append(name)
    #     data = {
    #         "videoNumberName": name,
    #         "goodJob": goodJob,
    #         "hot": hot,
    #         "fansClubNum": fansClubNum,
    #         "videoBroadcastGoodsList": videoBroadcastGoodsList,
    #         "startedAt": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
    #         "title": title,
    #         "watchedNum": watchedNum,
    #         "snapPic": livingPhotoUrl,
    #         "viewTrendList": [{"ts":int(round(time.time() * 1000)),
    #                            "v":watchedNum}]
    #     }
    #     liveDetailDictList.append(data)
    #     notice(name,time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    #
    #     return liveList,liveDetailDictList
    # # 直播结束，上传检测到的数据，从正在直播库移除
    # elif existFlag == True and liveStatusFlag == False:
    #     data = {}
    #     for i in liveDetailDictList:
    #         if i['videoNumberName'] == name:
    #             data = i
    #             liveDetailDictList.remove(i)
    #     data["endedAt"] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    #     print(data)
    #     upload_data(data)
    #     liveList.remove(name)
    #     return liveList, liveDetailDictList
    # elif existFlag == True and liveStatusFlag == True:
    #     for i in liveDetailDictList:
    #         if i['videoNumberName'] == name:
    #             if watchedNum > 0:
    #                 i["viewTrendList"].append({"ts":int(round(time.time() * 1000)),
    #                            "v":watchedNum})
    #                 i["watchedNum"] = watchedNum
    #             if goodJob > 0:
    #                 i["goodJob"] = goodJob
    #             if hot > 0:
    #                 i["hot"] = hot
    #     return liveList, liveDetailDictList
    # else:
    #     return liveList,liveDetailDictList

def chatWithGroup(d):
    if d.xpath('//*[@resource-id="com.tencent.mm:id/a27"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/a27"]').click()
    elif d.xpath('//*[@resource-id="com.tencent.mm:id/x1"]').exists:
        d.xpath('//*[@resource-id="com.tencent.mm:id/x1"]').click()
    for i in (1,4,1):
        if d.xpath('//*[@resource-id="com.tencent.mm:id/b4a"]').exists:
            d.xpath('//*[@resource-id="com.tencent.mm:id/b4a"]').click()
        elif d.xpath('//*[@resource-id="com.tencent.mm:id/iki"]').exists:
            d.xpath('//*[@resource-id="com.tencent.mm:id/iki"]').click()
        d(focused=True).send_keys(chatData.data[numpy.random.randint(0, 99)])
        d.xpath("//*[re:match(@text, '发送.*')]").click()

#截图
def getScreenShot(d):
    print(getScreenShot)
    # 截图保存到电脑上
    screen_path = "C:\\Users\\有赞\\Desktop\\直播监控\\screen_shot\\"
    img_name = str(int(time.time() * 1000000)) + '.png'
    screen_save_path = screen_path + img_name
    d.screenshot().save(screen_save_path)
    # 上传图片
    livingPhotoUrl = uploadImg.upload_img(img_name, screen_save_path)
    # livingPhotoUrl = "qa test"
    return livingPhotoUrl


#查看直播状态
def checkLiveStatus(d,name,incorrectNameList,liveDetailDictList,liveList):
    print("checkLiveStatus")
    watchedNum = 0
    goodJob = 0
    hot = 0
    fansClubNum = 0
    broadcastBlessBagFlaginteger = 0
    title = ""
    livingPhotoUrl = ""
    videoBroadcastGoodsList = []
    d.xpath(
        '//*[@resource-id="com.tencent.mm:id/iix"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]').wait(timeout=3.5)
    if d.xpath('//*[@resource-id="com.tencent.mm:id/iix"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]').exists:
        result = d.xpath('//*[@resource-id="com.tencent.mm:id/iix"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.TextView[1]').get_text()
        if result == name:
            if d.xpath('//*[@resource-id="com.tencent.mm:id/iix"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]').exists:
                d.xpath('//*[@resource-id="com.tencent.mm:id/iix"]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]').click()
                #todo check name
                if d.xpath('//*[@resource-id="com.tencent.mm:id/ivq"]/android.widget.RelativeLayout[1]/android.widget.TextView').exists:
                    if d.xpath('//*[@resource-id="com.tencent.mm:id/ivq"]/android.widget.RelativeLayout[1]/android.widget.TextView').get_text() != name:
                        d.press("back")
                        return False, incorrectNameList, goodJob, hot, title, watchedNum, videoBroadcastGoodsList, fansClubNum, livingPhotoUrl,broadcastBlessBagFlaginteger
                # 获取场观和热度
                watchedResult = getNums(d)
                watchedNum = watchedResult[0]
                # hot = watchedResult[1]
                # title = getLiveTheme(d)
                # goodJob = getGoodJob(d)
                fansClubNum = getFansClubNum(d)
                broadcastBlessBagFlaginteger = getbroadcastBlessBagFlaginteger(d)
                videoBroadcastGoodsList = getGoodsBagDetails(d)
                livingPhotoUrl = getScreenShot(d)
                if not d.xpath('//*[@resource-id="com.tencent.mm:id/egd"]').exists:
                    d.press("back")
                if d.xpath('//*[@resource-id="com.tencent.mm:id/dt_"]').exists:
                    d.xpath('//*[@resource-id="com.tencent.mm:id/dt_"]').click()
                return True, incorrectNameList,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger
            else:
                return False, incorrectNameList,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger
        else:
            if name not in incorrectNameList:
                incorrectNameList.append(name)
            return False, incorrectNameList,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger
    else:
        if name not in incorrectNameList:
            incorrectNameList.append(name)
        return False, incorrectNameList,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger


def runStart(device, wechatNames):

    liveDetailDictList = []
    liveList = []
    incorrectNameList = []
    try:
        # for device in devices:
        #     ds.append(u2.connect(device))
        # for d in ds:
        #     print("into wechat video search")
        #     intoWechat(d)
        d = u2.connect(device)
        d.watcher.when('确定').click()
        d.watcher.start()
        intoWechat(d)
        # 直播间停留时间
        waitTime = 1
        count = 1
        while 1:
            try:
                name = getOneSnapVideoNumberName()
                # name = "香雅形体女子课堂"
                if name != "Empty":
                    currentHour = int(datetime.datetime.now().strftime('%H'))
                    currentMinutes = int(datetime.datetime.now().strftime('%M'))
                    if (currentHour >=8 and currentHour <= 23) or (currentHour >=0 and currentHour < 1):
                        if currentMinutes >= 30 and currentMinutes < 35:
                            time.sleep(600)
                        print(name)
                        existFlag = False
                        searchName(d, name)
                        liveStatusFlag,incorrectNameList,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger = checkLiveStatus(d,name,incorrectNameList,liveDetailDictList,liveList)
                        print(incorrectNameList)
                        liveList,liveDetailDictList = resultCheck(liveList,liveDetailDictList,existFlag,liveStatusFlag,name,goodJob,hot,title,watchedNum,videoBroadcastGoodsList,fansClubNum,livingPhotoUrl,broadcastBlessBagFlaginteger)
                        print(liveList,liveDetailDictList)
                        if count % 50 == 0:
                            intoWechatMain(d)
                            chatWithGroup(d)
                            intoWechat(d)
                        count += 1
                else:
                    time.sleep(5)

            except Exception as e:
                print("流程异常", e)
                # error_log(other=e)
                intoWechat(d)
                # continue

    except Exception as e:
        print("主流程异常", e)
        # error_log(other=e)
        reStartDevices()
        runStart(device, "name")



def getOneSnapVideoNumberName():
    print("getOneSnapVideoNumberName")
    url = "http://gw.guang.com/guang-app-util/api/automator/getOneSnapVideoNumberName"
    res = requests.get(url)
    print({"进入直播间的视频号":res.json()})
    if 'data' in res.json():
        name = res.json()['data']
        return name
    else:
        print("No name get ")
        return "Empty"
        #todo add notify

def reStartDevices():
    os.system('''adb reconnect offline''')




def get_devices():
    '''获取已经链接的手机id'''
    # devices_info = os.popen("C:\\Users\\有赞\\Desktop\\platform-tools\\adb.exe devices -l").read()
    devices_info = os.popen('''%sadb.exe devices -l''' % adb_path).read()
    splited_devices = devices_info.split('\n')[1:]


    result_list = []
    for device in splited_devices:
        if device:
            id = re.findall("(\w+) +device product", device)[0]
            result_list.append(id)
    # for d in result_list:
        # clear(d)
    #     reboot(d)

    print(result_list)
    return result_list

def clear(devices):
    d = u2.connect(devices)
    d.press("home")
    d(resourceId="com.miui.home:id/icon_title", text="手机管家").click()
    if d(resourceId="com.miui.securitycenter:id/bar_title", text="手机管家").exists:
        d(resourceId="com.miui.securitycenter:id/bar_title", text="手机管家").click()
    for i in range(5):
        if not  d(resourceId="com.miui.securitycenter:id/title", text="微信专清").exists:
            d.swipe(0.5, 0.7, 0.5, 0.3, 0.2)
    d(resourceId="com.miui.securitycenter:id/title", text="微信专清").click()

def reboot(d):
    # 重启
    os.system('''%sadb.exe kill-server'''%adb_path)
    time.sleep(3)
    print(d)
    x='''%sadb.exe -s %s reboot'''%(adb_path,d)
    os.system(x)

def thread_run():
    devices = get_devices()
    thread = []
    os.system('''%sadb.exe kill-server ''' % adb_path)
    os.system('''%sadb.exe start-server ''' % adb_path)
    time.sleep(3)


    # wechatNames = [i for i in wechatNames if i != '']
    for device in devices:
        #i//2
        # wechatNames = getNameFromXls("C:\\Users\\有赞\\Desktop\\直播监控\\基础.xlsx", i//2, 0)
        # wechatNames = getNameFromXls("C:\\Users\\有赞\\Desktop\\直播监控\\test.xlsx", i // 2, 0)
        wechatNames = []
    # for i in range(0, 2, 2):
        thread.append(threading.Thread(target=runStart, args=(device, wechatNames)))


    # for i in devices:
    #     thread.append(threading.Thread(target=runStart, args=(i,)))  # 创建一个线程
        # t.start()  # 启动线程
    for t in thread:
        t.start()

    for t in thread:
        t.join()

if __name__ == '__main__':
    thread_run()